package cn.vire.electric.simulation.controller;

import cn.vire.electric.simulation.common.dto.Result;
import cn.vire.electric.simulation.config.context.TC;
import cn.vire.electric.simulation.config.executor.AsyncScheduler;
import cn.vire.electric.simulation.config.interceptor.AuthenticationInterceptor;
import cn.vire.electric.simulation.config.properties.StatisticsProperty;
import cn.vire.electric.simulation.pojo.LoginUserDto;
import cn.vire.electric.simulation.pojo.TestDto;
import cn.vire.electric.simulation.utils.InetAddressUtil;
import cn.vire.electric.simulation.utils.JwtHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.SameSiteCookies;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Duration;
import java.util.List;

@RestController
@Api(tags = "用户管理相关接口")
//@ApiIgnore("关闭接口文档,保留运维工具集")
@RequestMapping("/user")
@Slf4j
public class UserController {

    private final static Logger logger = LoggerFactory.getLogger(UserController.class);
    @Resource
    private ApplicationEventPublisher applicationEventPublisher;
    @Resource
    private AsyncScheduler asyncScheduler;

    @Value("${biz.front.index:}")
    private String jumpPage;

    @ApiOperation(value = "用户跳转登录")
    @GetMapping("/jump-login")
    public void loginAuth(@RequestParam @ApiParam("用户名") String name,
                          @RequestParam @ApiParam("ID") Long id,
                          @RequestParam(required = false,defaultValue = "2") @ApiParam("角色:1:管理员;2:用户") Integer role,
                          HttpServletResponse response) throws IOException {
        logger.info("用户校验开始");
        LoginUserDto loginUserDto = new LoginUserDto();
        loginUserDto.setId(id);
        loginUserDto.setName(name);
        loginUserDto.setRole(role);
        String token = JwtHelper.createToken(loginUserDto);

        ResponseCookie cookie = ResponseCookie.from(AuthenticationInterceptor.USER_TOKEN_HEAD, token) // key & value
                .httpOnly(false)     // 禁止js读取
                .secure(false)      // 在http下也传输
                .path("/")          // path
                .maxAge(Duration.ofDays(7))    // 过期
                .sameSite(SameSiteCookies.LAX.getValue())    // 大多数情况也是不发送第三方 Cookie，但是导航到目标网址的 Get 请求除外
//                            .domain(domain)
                .build();
        response.setHeader(HttpHeaders.SET_COOKIE, cookie.toString());
        // 重定向到首页
        response.sendRedirect(StringUtils.isEmpty(this.jumpPage) ? "/" : this.jumpPage);
    }

    @ApiOperation(value = "当前登录用户信息")
    @GetMapping("/current/detail")
    public Result<LoginUserDto> getUserInfo() {
        LoginUserDto userInfo = TC.getUserInfo();
        return Result.ok(userInfo);
    }

    public static void main(String[] args) {
    }


    @Resource
    private StatisticsProperty statisticsTypProperty;
    @ApiOperation(value = "测试接口")
    @PostMapping("/test")
    @Transactional
    public Result<List<StatisticsProperty.StatisticsCategory>> loginAuth(@RequestBody @Validated() TestDto testDto) throws InterruptedException {
        log.info("host[{}]", InetAddressUtil.getInetAddress());
//        this.applicationEventPublisher.publishEvent(testDto);
//        this.asyncScheduler.demo();
        return Result.ok(statisticsTypProperty.getCategories());
    }


}
